<template>
	<popup ref="popupRef" title="转账" width="500px" @confirm="handleConfirm" :async="true" @close="popupClose">
		<div class="pr-8">
			<el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
				<el-form-item label="USDT金额"> {{ value }} </el-form-item>
				<el-form-item label="转账金额" prop="num">
					<el-input :model-value="formData.num" placeholder="请输入转账金额" type="number"
						@input="numberValidate" />
				</el-form-item>
				<el-form-item label="转入地址" prop="in_addr">
					<el-input v-model="formData.in_addr" placeholder="请输入转入地址" clearable />
				</el-form-item>
			</el-form>
		</div>
	</popup>
</template>
<script lang="ts" setup>
	import Popup from '@/components/popup/index.vue'
	import type { FormInstance, FormRules } from 'element-plus'
	import feedback from '@/utils/feedback'
	const formRef = shallowRef<FormInstance>()
	const props = defineProps({
		show: {
			type: Boolean,
			required: true
		},
		value: {
			type: [Number, String],
			required: true
		}
	})
	const emit = defineEmits<{
		(event : 'update:show', value : boolean) : void
		(event : 'confirm', value : any) : void
	}>()
	const formData = reactive({
		num: '',
		in_addr: '',
	})
	const popupRef = shallowRef<InstanceType<typeof Popup>>()


	const formRules : FormRules = {
		num: [
			{
				required: true,
				message: '请输入转账金额'
			}
		],
		in_addr: [
			{
				required: true,
				message: '请输入转入地址'
			}
		],
	}
	const numberValidate = (value : string) => {
		if (value.includes('-')) {
			return feedback.msgError('请输入正整数')
		}
		formData.num = value
	}
	const handleConfirm = async () => {
		await formRef.value?.validate()
		emit('confirm', formData)
	}

	const popupClose = () => {
		emit('update:show', false)
		formRef.value?.resetFields()
	}
	const adjustmentMoney = computed(() => {
		let money = Number(props.value) - Number(formData.num);
		return Math.round(money * 100) / 100;
	})
	watch(
		() => props.show,
		(val) => {
			if (val) {
				popupRef.value?.open()
			} else {
				popupRef.value?.close()
			}
		}
	)
	watch(adjustmentMoney, (val) => {
		if (val < 0) {
			feedback.msgError('钱包余额不足')
			formData.num = ''
		}
	})
</script>